<template>
    <van-icon 
        :color="value === 1? '#e5645f' :'#777'" 
        :name="value === 1 ? 'good-job' : 'good-job-o'" 
        :loading="loading"
        @click="onLike" 
    />
</template>

<script>
import { addLike, deleteLike } from '@/api/article'

export default {
    name: 'LikeArticle',
    props: {
        value: {
            type: Number,
            required: true
        },
        articleId: {
            type: [String, Number, Object],
            required: true
        }
    },
    data() {
        return {
            loading: true  // 点赞按钮加载状态，防止因为网络原因致使用户多次点击
        }
    },
    methods: {
        async onLike() {
            this.loading = true
            try {
                let status = -1
                if (this.value === 1) {
                    // 已点赞，取消点赞
                    await deleteLike(this.articleId)
                } else {
                    // 未点赞，添加点赞
                    await addLike(this.articleId)
                    status = 1
                }

                // 更新视图
                this.$emit('input', status)

                this.$toast.success(status === 1 ? '点赞成功' : '取消点赞' )
            } catch (err) {
                this.$toast.fail('操作失败，请重试！')
            } 
            this.loading = false
        }
    }
}
</script>

<style scoped lang="less">

</style>